package cn.huijielong.modules.pay.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import cn.huijielong.common.exception.VSException;
import cn.huijielong.common.props.PropsConfig;
import cn.huijielong.common.utils.LogMessage;
import cn.huijielong.common.utils.Query;
import cn.huijielong.common.wxpay.sdk.WXPay;
import cn.huijielong.common.wxpay.sdk.WXPayConstants;
import cn.huijielong.common.wxpay.sdk.WXPayUtil;
import cn.huijielong.modules.sys.service.impl.SimpleServiceImpl;

@Service("wXPayService")
public class WXPayService extends SimpleServiceImpl implements CommandLineRunner{
	@Autowired
	private PropsConfig propsConfig;
	private WXPay wxPay;
	private String name="微信支付";
	
	public Map<String,String> unifinedOrder(String openid,String orderNo,int payAmount){
		Map<String,String> data=new HashMap<>();
		data.put("out_trade_no", orderNo);
		data.put("openid", openid);
		data.put("total_fee", String.valueOf(payAmount));
		data.put("notify_url", propsConfig.getWxpay().getNotifyUrl());
		data.put("body", "千人团支付");
		data.put("spbill_create_ip", "140.143.34.142");
		data.put("trade_type", WXPayConstants.TRADE_TYPE_JSAPI);
		Query q=Query.empty(data);
		String logMsg=LogMessage.create(name, "下订单").getMsg(q);
		try {
			logger.info("{}开始...",logMsg);
			Map<String,String> resp = wxPay.unifiedOrder(data);
			logger.info("{}完成，返回结果：{}",logMsg,resp);
			return resp;
		} catch (Exception e) {
			logger.error("{}失败",logMsg,e);
			throw new VSException("下单失败");
		}
	}
	
	public Map<String,String> fillResponseData(Map<String, String> data) throws Exception{
		return wxPay.fillResponseData(data);
	}
	
	public Query getPayinfo(Map<String,String> data) {
		Query q=Query.empty();
		return q;
	}
	
	public void isSignatureValid(Map<String,?> data) {
		try {
			boolean b=WXPayUtil.isSignatureValid(data, propsConfig.getWxpay().getKey(), wxPay.getSignType());
			if(!b) {
				throw new VSException("签名不一致");
			}
		} catch (Exception e) {
			throw new VSException(e);
		}
	}

	@Override
	public void run(String... args) throws Exception {
		wxPay=new WXPay(propsConfig.getWxpay(), propsConfig.getWxpay().getNotifyUrl(), true);
		//支付需要传入数据
		Map<String,String> payMap=new HashMap<>();
		payMap.put("out_trade_no", "");
		payMap.put("openid", "");
		payMap.put("total_fee", "");
	}
}
